package com.streetsmart.main;
/**
 * Displays the schedule to the user. Provides a list view and map view can be seen by hitting the map button
 */
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;

import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Button;
import com.streetsmart.Algorithm;
import com.streetsmart.DBManager;
import com.streetsmart.LocationService;
import com.streetsmart.MapRouteActivity;
import com.streetsmart.MyBusiness;
import com.streetsmart.MyEvent;
import com.streetsmart.MyLocation;
import com.streetsmart.R;
import com.streetsmart.ScheduleListItem;
import com.streetsmart.StartScheduleNavigation;
import com.streetsmart.Utilities;

public class SSScheduleDisplayActivity extends Activity {

	Context context = this;
	TextView totalDistance;
	TextView totalTime;
	TextView savings;
	ListView scheduleList;
	Algorithm alg = null;
	Intent intent;
	DBManager db;
	Cursor cur;
	ArrayList<ScheduleListItem> schedule;
	private static final int MY_DATA_CHECK_CODE = 0;
	boolean isTTSInstalled = false;
	static Intent ServiceIntent;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.ssschedule_display);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.sswindow_title);
		scheduleList = (ListView) findViewById(R.id.listViewScheduleDisplay);
		intent = getIntent();
		Bundle b = intent.getExtras();
		float timeInHand = b.getFloat("time");
		double latitude = b.getDouble("latitude");
		double longitude = b.getDouble("longitude");
		String address = b.getString("address");
		MyLocation returnAddress = new MyLocation(latitude, longitude, address);
		MyLocation startAddress = null;
		if (b.getBoolean("isCurrent")) {
			startAddress = returnAddress;
		} else {
			db = new DBManager(context);
			cur = db.getMostRecentLocation();
			if (cur.getCount() > 0) {
				cur.moveToFirst();
				double lat = cur.getDouble(1);
				double lng = cur.getDouble(2);
				try {
					startAddress = new MyLocation(lat, lng);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			cur.close();
			db.close();
		}

		if (getLastNonConfigurationInstance() != null) {
			SavedObject savedObj = (SavedObject) getLastNonConfigurationInstance();

			alg = savedObj.getAsyncTask();
			alg.attach(this);
		} else {
			alg = new Algorithm(timeInHand, startAddress, returnAddress,
					context, this);
			alg.execute(this);
		}

		//StartScheduleNavigation.stopThisThread();
		/*
		 * alg = new Algorithm(timeInHand, startAddress, returnAddress,
		 * mcontext, this); try { schedule = alg.computeSchedule(); } catch
		 * (JSONException e) { } updateScheduleDisplay(schedule);
		 */}

	@Override
	public Object onRetainNonConfigurationInstance() {

		alg.detach();

		final SavedObject savedObj = new SavedObject();
		savedObj.setAsyncTask(alg);

		return savedObj;
	}

	public void onClickMap(View v) {
		Intent intent = new Intent(this, MapRouteActivity.class);
		startActivity(intent);
	}

	public void onClickLater(View v) {
		Utilities.setSchedule(null);
		if(ServiceIntent != null){
			this.stopService(ServiceIntent);
			ServiceIntent = null;
		}
		if(db == null){
			db = new DBManager(context);
		}
		db.updateAllInProgressEventsStatus(); //updates the in progress eventsback to unscheduled tasks
		db.close();
		finish();
	}

	/**
	 *  check if the tts data is installed and ready to use. before actually navigating through the schedule
	 * @param v
	 */
	public void onClickStart(View v) {
		if(ServiceIntent != null){
			this.stopService(ServiceIntent);
			ServiceIntent = null;
		}
		if(v.getId() == R.id.buttonStart){
			v.setEnabled(false);
		}
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == MY_DATA_CHECK_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
				// success, create the TTS instance
				isTTSInstalled = true;
				// mTts = new TextToSpeech(this, this);
			} else {
				// missing data, install it
				Intent installIntent = new Intent();
				installIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);
			}
		}
		startSchedule();
	}

	/**
	 * starts the service StartScheduleNavigation
	 */
	public void startSchedule() {
		
		ServiceIntent = new Intent(this, StartScheduleNavigation.class);
		ServiceIntent.putExtra("tts", isTTSInstalled);
		startService(ServiceIntent);
		
	}

	@Override
	public void onBackPressed() {
		finish();
	}

	public void updateSavingsDisplay() {
		// TODO From Algorithm calculate the values and display
		totalDistance.setText("12.5 miles");
		totalTime.setText("2 hrs 15 mins");
		savings.setText("7 miles and 1 hr 5 mins");
	}

	public void updatePointsForMap(ArrayList<ScheduleListItem> schedule) {
		Utilities.clearGeopoints();
		int count = schedule.size();
		MyEvent e;
		Double lat, lng;
		for (int i = 0; i < count; i++) {
			e = schedule.get(i).getEvent();
			lat = e.getLocation().getLatitude();
			lng = e.getLocation().getLongitude();
			Utilities.latitudeList.add(lat);
			Utilities.longitudeList.add(lng);
		}
	}

	public void updateScheduleDisplay(ArrayList<ScheduleListItem> schedule) {
		updatePointsForMap(schedule);
		scheduleList.setAdapter(new ScheduleAdapter(context,
				R.layout.schedule_list_item, schedule));
	}

}

class ScheduleAdapter extends ArrayAdapter<ScheduleListItem> {

	private ArrayList<ScheduleListItem> items;
	Context context;

	public ScheduleAdapter(Context context, int textViewResourceId,
			ArrayList<ScheduleListItem> items) {
		super(context, textViewResourceId, items);
		this.context = context;
		this.items = items;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.schedule_list_item, null);
		}
		ScheduleListItem s = items.get(position);
		if (s != null) {
			TextView ht = (TextView) v.findViewById(R.id.Headingtext);
			TextView tt = (TextView) v.findViewById(R.id.toptext);
			TextView bt = (TextView) v.findViewById(R.id.timetext);
			ImageView img = (ImageView) v.findViewById(R.id.Image);
			TextView rt = (TextView) v.findViewById(R.id.ratingtext);

			if (ht != null) {
				String type = s.getEvent().getType();
				if (type.equals("Must")) {
					ht.setText(s.getEventName());
					if (tt != null) {
						tt.setText("Venue:\t" + s.getAddress());
					}
				} else {
					ht.setText(s.getBusinessName());
					if (tt != null) {
						tt.setText(s.getEventName() + " at " + s.getAddress());
					}
				}
			}

			if (bt != null) {
				bt.setText("At " + s.getStartingTime());
			}

			if (img != null) {
				String url = s.getImageUrl();
				if (url != null && !url.equals("building")) {

					try {
						URL ulrn = new URL(url);
						HttpURLConnection con = (HttpURLConnection) ulrn
								.openConnection();
						InputStream is = con.getInputStream();
						Bitmap bmp = BitmapFactory.decodeStream(is);
						if (null != bmp)
							img.setImageBitmap(bmp);
						else {
							con.disconnect();
							System.out.println("The Bitmap is NULL");
							img.setImageDrawable(context.getResources()
									.getDrawable(R.drawable.building));

						}
						if (con != null) {
							con.disconnect();
						}
					} catch (Exception e) {
					}
				} else {
					img.setImageDrawable(context.getResources().getDrawable(
							R.drawable.building));
				}
			}

			if (rt != null) {
				String rating = s.getRatings();
				rt.setText(rating.length() > 0 ? "Rating :" + s.getRatings()
						: "");
			}
		}
		return v;
	}

}

class SavedObject {
	private Algorithm asyncTask;

	public void setAsyncTask(Algorithm asyncTask) {
		this.asyncTask = asyncTask;
	}

	public Algorithm getAsyncTask() {
		return asyncTask;
	}
}
